package com.smz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smz.dao.ParDAO;
import com.smz.dao.SCompanyDAO;
import com.smz.dao.TRelationDAO;
import com.smz.entity.SCompany;
import com.smz.entity.TPar;
import com.smz.entity.TRelation;
import com.smz.service.TRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

@Service
public class TRelationServiceImpl extends ServiceImpl<TRelationDAO, TRelation>implements TRelationService {
    @Autowired
    TRelationDAO tRelationDAO;
    @Autowired
    SCompanyDAO sCompanyDAO;
    @Autowired
    ParDAO parDAO;

    @Override
    public String addTRelation(TPar tPar, String mage) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SCompany sCompany = sCompanyDAO.selectCompanyByLegal(principal.getUsername());
        if(sCompany.getCompanyName().equals(tPar.getSCompanyB().getCompanyName())){
            TRelation tRelation1 = tRelationDAO.selectRelation(Integer.parseInt(tPar.getTParComB()), Integer.parseInt(tPar.getTParComA()));
            if(tRelation1!=null){
                return "已存在合作关系";
            }
            if(mage.equals("ok")){
                TRelation tRelation = new TRelation(0,sCompany.getBusinessScope(),tPar.getTParDesc(),Integer.parseInt(tPar.getTParComB()),Integer.parseInt(tPar.getTParComA()));
                tRelationDAO.insert(tRelation);
                tPar.setTParStatus("已处理");
                tPar.setTParStatus2("已通过");
                parDAO.updateById(tPar);
                return "通过合作，成为该公司客户！";
            }else {
                tPar.setTParStatus("已处理");
                tPar.setTParStatus2("未通过");
                parDAO.updateById(tPar);
                return "处理完成，未通过申请！";
            }

        }else {
            return "对方还在审核中！";
        }
    }

    @Override
    public int removeRelation(int kid) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SCompany sCompany = sCompanyDAO.selectCompanyByLegal(principal.getUsername());
        return tRelationDAO.deleteRelation(sCompany.getCompanyId(),kid);
    }
}
